<template>
  <section class="sample-section"  v-loading.lock="loading" element-loading-text="拼命加载中">
    <el-form :model="dataForm" @keyup.enter.native="getDataList()" label-width="80px">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="12" :lg="4" :xl="4">
          <el-form-item label="公司名称" prop="company_id">
            <el-select v-model="dataForm.company_id" filterable placeholder="选择公司名称">
              <el-option value="">全部</el-option>
              <el-option
                v-for="item in companys"
                :key="item.id"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="4" :xl="4">
          <el-form-item label="批次号" prop="batch_number">
            <el-input v-model="dataForm.batch_number" type="text" placeholder="批次号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6">
          <el-form-item label="录入时间" prop="sale">
            <el-date-picker
              v-model="dataForm.created_at"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="20" :sm="20" :md="6" :lg="6" :xl="6">
          <el-form-item>
            <el-button type="primary" @click="getDataList()">查询</el-button>
            <el-button type="danger" @click="exportBatch()">导出</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table
      :data="dataList"
      border
      :row-class-name="rowClassName"
      v-loading="dataListLoading"
      @sort-change="changeSort"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        width="80"
        label="ID">
      </el-table-column>
      <el-table-column
        prop="batch_number"
        header-align="center"
        align="center"
        width="180"
        label="批次号">
      </el-table-column>
      <el-table-column
        prop="company_info.title"
        header-align="center"
        align="center"
        label="企业名称">
      </el-table-column>
      <el-table-column
        prop="date"
        header-align="center"
        align="center"
        width="120"
        label="结算周期">
      </el-table-column>
      <el-table-column
        prop="created_at"
        header-align="center"
        align="center"
        label="导入时间">
      </el-table-column>
      <el-table-column
        prop="settle_money"
        header-align="center"
        align="center"
        width="120"
        label="实付总额">
          <template slot-scope="scope">
            <span>{{scope.row.settle_money|numFilter}}</span>
          </template>
      </el-table-column>
      <el-table-column
        prop="import_type"
        header-align="center"
        align="center"
        width="120"
        label="导入类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.import_type === 1" size="small" type="warning">后台导入</el-tag>
          <el-tag v-else-if="scope.row.import_type === 2" size="small" type="success">企业导入</el-tag>
          <el-tag v-else-if="scope.row.import_type === 3" size="small" type="info">开放API</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="pay_status"
        header-align="center"
        align="center"
        width="120"
        label="支付状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.pay_status === -1" size="small" type="warning">打款失败</el-tag>
          <el-tag v-else-if="scope.row.pay_status === 1" size="small" type="info">等待打款</el-tag>
          <el-tag v-else-if="scope.row.pay_status === 2" size="small" type="">打款中</el-tag>
          <el-tag v-else-if="scope.row.pay_status === 3" size="small" type="danger">部分打款</el-tag>
          <el-tag v-else size="small" type="success">打款成功</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="140"
        label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('payment:details')" type="primary" size="small" @click="jumpTourl('payment-details', scope.row.id)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </section>
</template>

<script>
  export default {
    data () {
      return {
        dataForm: {
          company_id: '',
          batch_number: '',
          import_type: [1, 2, 3],
          pay_status: [9],
          created_at: '',
          sort_by: '',
          order_by: ''
        },
        loading: false,
        dataList: [],
        search: {
          title: '',
        },
        companys: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
      }
    },
    components: {
    },
    mounted() {
      console.log('mounted')
      this.init()
    },
    activated () {
      console.log('activated')
      this.getDataList()
    },
    methods: {
      init () {
        this.$http({
          url: this.$http.adornUrl('/company/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 300,
            'title': this.search.title
          })
        }).then(({data}) => {
          let _list = data.page.list
          this.companys = _list.map(function(val, idx, _list) {
            return Object.assign({}, {'id': val.company_id, 'title': val.title})
          })
          setTimeout(() => {
            this.loading = false
          }, 500);
        })
      },
      rowClassName({row, rowIndex}) {
        if(row.is_jg) {
          return 'bgred';
        }
        return ''
      },
      changeSort(val) {
        if (val.order !== null) {
          this.dataForm.sort_by = val.prop
          this.dataForm.order_by = val.order === 'ascending' ? 'asc' : 'desc'
        } else {
          this.dataForm.sort_by = ''
          this.dataForm.order_by = ''
        }
        this.dataListLoading = true
        this.getCustomerList()
        this.dataListLoading = false
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.getCustomerList()
        this.dataListLoading = false
      },
      getCustomerList() {
        this.$http({
          url: this.$http.adornUrl('/payment/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'company_id': this.dataForm.company_id,
            'import_type': this.dataForm.import_type,
            'pay_status': this.dataForm.pay_status,
            'batch_number': this.dataForm.batch_number,
            'created_at': this.dataForm.created_at,
            'sort': this.dataForm.sort_by,
            'order': this.dataForm.order_by
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
            this.$message.error(data.msg)
          }
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      jumpTourl ( _url, _id) {
        this.$router.push({ name: _url, query: { id:  _id}})
      },
      exportBatch() {
        this.loading = true;
        this.$http({
          url: this.$http.adornUrl('/payment/batchexport'),
          method: 'get',
          responseType: 'blob',
          params: this.$http.adornParams({
            'company_id': this.dataForm.company_id,
            'import_type': this.dataForm.import_type,
            'pay_status': this.dataForm.pay_status,
            'batch_number': this.dataForm.batch_number,
            'created_at': this.dataForm.created_at,
          })
        }).then((res) => {
          let _data = res.data
          let blob = new Blob([_data])
          let reader = new FileReader()
          reader.readAsDataURL(blob)
          reader.onload = (e) => {
            let a = document.createElement('a')
            a.download = '多批次付款明细.csv'
            a.href = e.target.result
            document.body.appendChild(a)
            a.click()
            a.remove()
          }
          this.loading = false;
        }).catch((error) =>{
          console.log(error)
          this.loading = false;
        })
      }
    },
    filters: {
      // 截取当前数据到小数点后两位
      numFilter(value) {
        const realVal = parseFloat(value).toFixed(2);
        return realVal;
      }
    }
  }
</script>

<style lang="scss">
  .bgred {
    background-color: #fab6b6 !important;
  }
</style>
